package com.woniuxy.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.nio.charset.Charset;

@Configuration
public class RedisConfig {

            @Bean
            public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
                RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
                redisTemplate.setConnectionFactory(redisConnectionFactory);
                //创建一个json的序列化对象
                GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
                //设置value的序列化方式json
                redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
                RedisSerializer<String> stringSerializer = new StringRedisSerializer(Charset.forName("UTF-8"));
                //设置key序列化方式String
                redisTemplate.setKeySerializer( stringSerializer);
                //设置hash key序列化方式String
                redisTemplate.setHashKeySerializer( stringSerializer);
                //设置hash value序列化json
                redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
                redisTemplate.setDefaultSerializer(stringSerializer);
                redisTemplate.afterPropertiesSet();
                // 设置支持事务
                redisTemplate.setEnableTransactionSupport(true);
                redisTemplate.afterPropertiesSet();
                return redisTemplate;
            }

            @Bean
            public RedisSerializer<Object> redisSerializer() {
                //创建JSON序列化器
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
                //必须设置，否则无法将JSON转化为对象，会转化成Map类型
                objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
                return new GenericJackson2JsonRedisSerializer(objectMapper);
            }




}
